package com.tys.algorithm.bak.test;

import java.util.Stack;

//使用数组实现栈
public class Code14_ArrayToStack {

    public static class MyStack {
        private int[] arr;
        private int index;
        private final int limit;

        public MyStack(int limit) {
            arr = new int[limit];
            index = 0;
            this.limit = limit;
        }

        public void push(int value) {
            if (index < limit) {
                arr[index++] = value;
            } else {
                throw new RuntimeException("full");
            }
        }

        public int pop() {
            if (index > 0) {
                return arr[--index];
            } else {
                throw new RuntimeException("empty");
            }
        }

        public boolean isEmpty() {
            return index == 0;
        }
    }


    //判断是否相等
    public static boolean isEqual(Integer o1, Integer o2) {
        if (o1 == null && o2 != null) {
            return false;
        }

        if (o1 != null && o2 == null) {
            return false;
        }

        if (o1 == null && o2 == null) {
            return true;
        }
        boolean flag = o1.equals(o2);
        if (!flag) {
            System.out.println("o1:" + o1 + " o2:" + o2);
        }
        return flag;
    }

    public static void main(String[] args) {
//        int[] arr = new int[32];
//        int index = 0;
//        arr[index++]  = 3;
//        System.out.println(arr[0] + " " + arr[1]);


        int oneTestDataNum = 100;
        int value = 10000;
        int testTimes = 100000;
        System.out.println("begin");
        for (int i = 0; i < testTimes; i++) {
//            System.out.println("i:" + i);

            int limit = (int) (Math.random() * value);
            MyStack myStack = new MyStack(limit);
            Stack<Integer> stack = new Stack<>();
            for (int j = 0; j < oneTestDataNum; j++) {
                int nums = (int) (Math.random() * value);
                if (stack.isEmpty()) {
                    myStack.push(nums);
                    stack.push(nums);
                } else {
                    if (Math.random() < 0.5) {
                        myStack.push(nums);
                        stack.push(nums);
                    } else {
                        if (!isEqual(myStack.pop(), stack.pop())) {
                            System.out.println("limit:" + myStack.limit);
                            System.out.println("index:" + myStack.index);
                            System.out.println("Oops1!");
                            return;
                        }
                    }
                }
            }
        }
        System.out.println("finish!");

    }


}
